<template>
  <div class='tinymce'>
    <h1>
      <el-row>
        <el-col :span="5">
          <span v-if="editActive">修改活动</span>
          <span v-else>添加活动</span>
          <el-button class="addBtn" @click="goBack">返回</el-button>
        </el-col>
        <!-- <el-col :span="19" style="text-align:right">
           <el-button v-if="article" type="primary" @click="submitArticle('formAling')">修改活动</el-button>
           <el-button v-else type="primary" @click="submitArticle('formAling')">保存活动</el-button>
        </el-col> -->
      </el-row>
    </h1>
    <div>
      
     <el-form  label-width="80px" :rules="aling" ref="formAling" :model="formLabelAlign">
      
        <el-form-item label="活动名称" prop="title" >
          <el-input v-model="formLabelAlign.name" style="width:60%"></el-input>
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker v-model="formLabelAlign.begin_time" type="date"  format="yyyy 年 MM 月 dd 日" value-format="timestamp" placeholder="选择日期"></el-date-picker> 至
          <el-date-picker v-model="formLabelAlign.end_time" type="date" format="yyyy 年 MM 月 dd 日" value-format="timestamp" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="活动医院" prop="hospital_name">
          <el-select v-model="formLabelAlign.hospital_name" @change="changeHospital" placeholder="请选择" style="width:60%">
            <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.hospital_id"></el-option>
          </el-select>
        </el-form-item>
       
        <el-form-item label="活动地址">
            <el-select v-model="ruleForm2.province"  @change="changeCity" filterable placeholder="选择省份" style="width:110px">
              <el-option v-for="item in ruleForm2.options1" :key="item.id" :label="item.areaname" :value="item.id" > </el-option>
            </el-select>
            <el-select v-model="ruleForm2.city" @change="changeArea" filterable placeholder="选择城市" style="width:110px">
              <el-option v-for="item in ruleForm2.options2" :key="item.id" :label="item.areaname" :value="item.id"> </el-option>
            </el-select>
            <el-select v-model="ruleForm2.area" @change="changeVal" filterable placeholder="选择区" style="width:110px">
              <el-option v-for="item in ruleForm2.options3" :key="item.id" :label="item.areaname" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="详细地址:" prop="position">
          <el-input  v-model="formLabelAlign.positaion" @blur="getLng" style="width:80%"></el-input>
          <div>
            <span>{{address}}</span>
            <span v-if="okLng== 1" style="margin-left:20px;color:#67c23a">经纬度获取成功</span>
            <span v-else-if="okLng== 2" style="margin-left:20px;color:red">无法获取该得知的经纬度获取</span>
            <span v-else></span>
          </div>
        </el-form-item>


         <el-form-item label="封面" prop="title">
          <!-- <el-upload
            :action="action"
            list-type="picture-card"
            :on-success="handleOkLogo"
            :data="postData"
            multiple>
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="formLabelAlign.logoImg" alt="">
          </el-dialog> -->

            <el-upload 
                class="avatar-uploaderInfo"
                :action="action"
                :show-file-list="false"
                :on-success="handleOkLogo"
                :before-upload="beforeAvatarUpload"
                :data="postData">
                <img v-if="formLabelAlign.logoImg" :src="formLabelAlign.logoImg" class="avatarInfo">
                <i v-else class="el-icon-plus avatar-uploader-iconInfo"></i>
              </el-upload>
        </el-form-item>
        <!-- <el-form-item label="链接" prop="link_url">
          <el-input v-model="formLabelAlign.link_url" style="width:60%"></el-input>
        </el-form-item> -->
        
      </el-form>
      
      <el-row>
        <div style="padding-left:20px;">
          <div class="initbox">
            <el-button class="initBtn" @click="upImageFun">图</el-button>
            <editor id='tinymce' v-model='tinymceHtml' :init='init'> </editor>
            
          </div>

          <el-button style="margin-top:20px" type="primary" @click="submitArticle('formAling')">提交活动</el-button>
        </div>
      </el-row>
    
    </div>
    <el-dialog :visible.sync="imgstuts">
      <el-upload
        class="upload-demo"
        :action="action"
        :on-success="handleOkContent"
        ref="upload"
        :data="postData"
        multiple
        >
        <el-button size="small" type="primary">添加图片</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="backFun">取 消</el-button>
        <el-button type="primary" @click="apendHtml">确 定</el-button>
      </span>
    </el-dialog>
     <div v-show="!showMap" id="XSDFXPage" class="XSDFXPage"></div>
  </div>
</template>

<script>
import {mapActions,mapMutations,mapGetters,mapState} from 'vuex'
import Http from '@/Http/Http'
import qnUrl from '@/Http/qiniuUrl'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/modern/theme'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'

export default {
  name: 'tinymce',
  props:['editActive'],
  data () {
    const title = (rule,value,callback) => {
      if (value === '') {
        callback(new Error('请输入标题'))
      } else {
        callback()
      }
    }
    
    return {

      action:qnUrl,//七牛的上传地址
      postData:{
        token:'',
      },
      dialogVisible: false,
      article:false,
      options:'',
      tokenimgUrl:'',
      formLabelAlign:{
        name:'',
        logoImg: '',
        positaion:'',
        hospital_name:'',
        end_time:'',
        begin_time:'',
        link_url:'',
      },
      aling:{
        title:[
          {validator:title,trigger:'blur'}
        ]
      },

      imgstuts:false, //富文本编辑器部分
      tinymceHtml:'',
      fileList:[],
      init: {
        language_url: '/static/tinymce/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/static/tinymce/skins/lightgray',
        height: 300,
        plugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',
        toolbar:
          'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image | removeformat',
        branding: false
      },

      getAreaOk:true,
      showMap:true,//是否显示地图
      address:'',//获取的地址
      okLng:0, //状态
      ruleForm2: {       
        options1:[],
        options2:[],
        options3:[],
        province:'',//省
        city:'',//市
        area:'',//区
      },
      mapdata:{ //地址的经纬度
        lat:'',
        lng:''
      },
    }
    
  },

  
  created() {
    this.getAllHospt();
    this.getToken()
    Http.getAreaList(0)
    .then( res => {
      this.ruleForm2.options1 = res.data.data;
    })
  },

  mounted() {
           
      // 百度地图API功能
      // 创建Map实例
      this.map = new BMap.Map("XSDFXPage",{enableMapClick:true});
      this.map.centerAndZoom("深圳",12);           
      this.map.enableScrollWheelZoom();    //启用滚轮放大缩小，默认禁用
      this.map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用

      this.map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
      this.map.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件
      this.map.addControl(new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT }));   //右下角，打开

      this.localSearch = new BMap.LocalSearch(this.map);
      this.localSearch.enableAutoViewport(); //允许自动调节窗体大小
      
    //this.map.addEventListener("click", this.showInfo);
  },

  methods:{
    getToken() {
      if(this.editActive){
        this.formLabelAlign.name = this.editActive.name;//名称
        this.formLabelAlign.hospital_name = this.editActive.hospital_id;//医院
        this.formLabelAlign.link_url = this.editActive.link_url; //链接
        this.formLabelAlign.logoImg = this.editActive.logo_url; //图片
        this.formLabelAlign.positaion = this.editActive.positaion; //地址
        this.formLabelAlign.begin_time = this.editActive.begin_time; //地址
        this.formLabelAlign.end_time = this.editActive.end_time; //地址
        this.tinymceHtml = this.editActive.content;


        this.ruleForm2.province = this.editActive.province_id;
        this.ruleForm2.city = this.editActive.city_id;
        this.ruleForm2.area = this.editActive.area_id;
        
        this.mapdata.lat = this.editActive.lat;
        this.mapdata.lng = this.editActive.lng;
         
        if(this.editActive.province_id){
          this.changeCity(this.editActive.province_id,this.editActive.city_id)
        }
        if(this.editActive.city_id){
          this.changeArea(this.editActive.city_id,this.editActive.area_id)
        }
      }
      Http.QiniuToken({})
      .then( res => {
        this.postData.token = res.data.data.uptoken;
        this.tokenimgUrl = res.data.data.domain
      })
      .catch( error => {
        this.$router.push('/')
        
      })
    },
    
    getAllHospt() {
      Http.getAllHospt()
      .then( res => {
        this.options = res.data.data
      })
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      if (isJPG || isPNG) {
        return true;
      } else {
          this.$message.error('上传图片格式不正确!');
        return false;
      }
    },

    handleOkLogo(responed) {
      this.formLabelAlign.logoImg = `http://${this.tokenimgUrl}/${responed.key}`
    },
   
    submitArticle(val) {
      
      this.$refs[val].validate((valid) => {
       
        if (valid) {
          if (!this.formLabelAlign.logoImg) {
            this.$message.error('请上传活动封面图')
            return
          }
          if (!this.formLabelAlign.name) {
            this.$message.error('请输入活动标题')
            return
          }
          if (!this.formLabelAlign.hospital_name) {
            this.$message.error('请选择活动医院')
            return
          }
          if (!this.formLabelAlign.positaion) {
            this.$message.error('请输入活动地址')
            return
          }
          if (!this.formLabelAlign.begin_time) {
            this.$message.error('请选择活动开始时间')
            return
          }
          if (!this.formLabelAlign.end_time) {
            this.$message.error('请选择活动结束时间')
            return
          }
          if (!this.tinymceHtml) {
            this.$message.error('请输入活动内容')
            return
          }
          const articleContent = this.tinymceHtml.replace(/30%/g,'100%');
          const param = {
            "name":this.formLabelAlign.name, //活动名称
            "hospital_id":this.formLabelAlign.hospital_name,  //医院
            "logo_url":this.formLabelAlign.logoImg,  //图片
            "content":articleContent, // 文章内容
            "positaion":this.formLabelAlign.positaion,
            "area_id":this.ruleForm2.area, //区
            "city_id":this.ruleForm2.city, //市
            "province_id":this.ruleForm2.province, //省
            "lng":this.mapdata.lng,
            "lat":this.mapdata.lat,
            "begin_time":this.formLabelAlign.begin_time,
            "end_time":this.formLabelAlign.end_time,
            "link_url":this.formLabelAlign.link_url,
            "status":1,
          };
          if (this.editActive) {
            param.id = this.editActive.id;
            this.postEditAriticeFun(param)
          } else {
            this.addAriticeFun(param)
          }
          
        } else {
          this.$message.error('请填写标题')
        }
      })
      
    },
    addAriticeFun(param) {
      Http.addActivity(param)
        .then( res => {
          if( res.data.code == 200 ){
            this.$message.success('活动发布成功')
            this.goBack()         
          } else if(res.data.code == -1003) {
            this.$message.error(`请求失败原因：${res.data.message}`)
            this.$router.push('/')
          }
        })
        .catch( error => {
          this.$message.error('服务器请求失败')
        })
    },
    postEditAriticeFun(param) {
      Http.editActive(param)
      .then( res => {
        if( res.data.code == 200 ){
          this.$message.success('活动修改成功')
          this.goBack()         
        } else if(res.data.code == -1003) {
          this.$message.error(`请求失败原因：${res.data.message}`)
          this.$router.push('/')
        }
      })
      .catch( error => {
        this.$message.error('服务器请求失败')
      })
    },
    goBack(){
      this.$emit('getlist')
    },
    
    //富文本编辑器部分
    upImageFun(){
      this.imgstuts = true
    },
    // 编辑器 上传图片的内容  - --------------
    
    handleOkContent(responed){
      this.fileList.push(`http://${this.tokenimgUrl}/${responed.key}`)
    },
     // 编辑器 上传图片的内容  - --------------
    backFun(){
      this.imgstuts = false;
      this.fileList =[]
      this.$refs.upload.clearFiles(); 
    },
    apendHtml(){
      let arrHtml='';
      this.fileList.forEach(item => {
        arrHtml += `<img style="width:30%" src="${item}" alt=""/>`;
      })
      this.tinymceHtml = `${this.tinymceHtml}${arrHtml}`;
      this.imgstuts = false
      this.fileList =[]
      this.$refs.upload.clearFiles(); 
    },

    //选中医院 获取对应的 地址经纬度
    changeHospital(val){

      this.options.forEach(item =>{
        if(item.hospital_id == val){
          this.ruleForm2.province = '';
          this.ruleForm2.city = '';
          this.ruleForm2.area = '';

          this.ruleForm2.province = item.province_id;
          this.ruleForm2.city = item.city_id;
          this.ruleForm2.area = item.area_id;
          this.formLabelAlign.positaion = item.position;
          this.mapdata.lat = item.lat;
          this.mapdata.lng = item.lng;
         
          if(item.province_id){
            this.changeCity(item.province_id,item.city_id)
          }
          if(item.city_id){
            this.changeArea(item.city_id,item.area_id)
          }
        }
      })
      
    },


    //获取地址部分
    changeCity(val,city=''){
      this.okLng = 0;
      Http.getAreaList(val)
        .then( res => {
          this.ruleForm2.options2 = res.data.data;
          this.ruleForm2.city = city;
        })
    },
    changeArea(val,are=''){
      this.okLng = 0;
      Http.getAreaList(val)
        .then( res => {
          this.ruleForm2.area = are;
          this.ruleForm2.options3 = res.data.data;
          if(this.getAreaOk){
            setTimeout(()=>{
              this.getLng()
            },50)
          }
          this.getAreaOk = true;
          
        })
    },
    changeVal(val){
      this.okLng = 0;
    },
    getLng() {
      let a,b,c;
      this.ruleForm2.options1.forEach(item => {
        if(item.id == this.ruleForm2.province){
          a = item.areaname
        }
      })
      if(this.ruleForm2.options2){
         this.ruleForm2.options2.forEach(item => {
          if(item.id == this.ruleForm2.city){
            b = item.areaname
          }
        })
      }
      if(this.ruleForm2.options3){
        this.ruleForm2.options3.forEach(item => {
          if(item.id == this.ruleForm2.area){
            c = item.areaname
          }
        })
      }
      if(!a || !b || !c){
        this.$message.error('请选择省，市，区');
        return
      }
      this.address = `${a}${b}${c}${this.formLabelAlign.positaion}`;
      this.searchByStationName()

    },
    searchByStationName() {
      this.okLng = 0;    
      this.map.clearOverlays();//清空原来的标注
      var keyword = this.address;
      const _this = this;
      this.localSearch.setSearchCompleteCallback(function (searchResult) {
          
          var poi = searchResult.getPoi(0);
          
          if(!poi){
            _this.okLng = 2;
            return
          }
          _this.vala = poi.point.lng + "," + poi.point.lat;
          _this.mapdata.lng = poi.point.lng;
          _this.mapdata.lat = poi.point.lat;
          if(_this.mapdata.lng){
            _this.okLng = 1;
          } else {
            _this.okLng = 2;
          }
          _this.map.centerAndZoom(poi.point, 13);
          var marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat));  // 创建标注，为要查询的地方对应的经纬度
          _this.map.addOverlay(marker);
          var content = _this.aderss + "<br/><br/>经度：" + poi.point.lng + "<br/>纬度：" + poi.point.lat;
          var infoWindow = new BMap.InfoWindow("<p style='font-size:14px;'>" + content + "</p>");
          marker.addEventListener("click", function () { this.openInfoWindow(infoWindow); });
          // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
      });
      _this.localSearch.search(keyword);
    },
  },
  components: {
    Editor,
  }
}
</script>
<style>
.el-textarea__inner{
  height:146px
}
.initbox{
  position: relative;
}
.initBtn{
  position: absolute;
  opacity: 0;
  position: absolute;
  z-index: 2;
  top: 36px;
  left: 786px;
  width: 30px;
  padding: 0;
  height: 33px;
  border: 1px solid red;
}

#tinymce_ifr{
  height:500px !important
}

.avatar-uploaderInfo .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploaderInfo .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-iconInfo {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatarInfo {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
